package org.bbl.web.panel;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.protocol.http.servlet.ServletWebRequest;
import org.apache.wicket.request.cycle.RequestCycle;
import org.bbl.db.domain.Bbl;
import org.bbl.db.domain.Book;
import org.bbl.utils.SendMail;

/**
 * @author biniam.gebremichael
 * @since 4/15/13
 */
public class ReportTypo extends Panel {
    private final Bbl bbl;
    private final Book book;

    String correction, comment;

    public String getCorrection() {
        return correction;
    }

    public void setCorrection(String correction) {
        this.correction = correction;
    }

    public String getComment() {
        return comment;
    }

    public void setComment(String comment) {
        this.comment = comment;
    }

    public ReportTypo(String id, final Bbl bbl,final Book book, final ModalWindow m) {
        super(id);
        this.bbl = bbl;
        this.book = book;
        add(new Label("header", book.getMidName() + bbl.getShortNumber()));
        add(new AjaxLink("close") {
            public void onClick(AjaxRequestTarget target) {
                m.close(target);
            }
        });

        setCorrection(bbl.getVerse());

        Form<Void> form = new Form<Void>("editForm");
        form.setMultiPart(true);
        form.add(new TextArea<ReportTypo>("correction", new PropertyModel<ReportTypo>(this, "correction")));
        form.add(new TextArea<ReportTypo>("comment", new PropertyModel<ReportTypo>(this, "comment")));
        form.add(new AjaxButton("submit") {
            @Override
            protected void onSubmit(AjaxRequestTarget ajaxRequestTarget, Form<?> components) {
                String ip = ((ServletWebRequest) RequestCycle.get().getRequest()).getContainerRequest().getRemoteAddr();
                String body = SendMail.compose(bbl, ip, book.getMidName(),getCorrection(), getComment());
                SendMail.send(body);
                m.close(ajaxRequestTarget);
            }

            @Override
            protected void onError(AjaxRequestTarget ajaxRequestTarget, Form<?> components) {
                m.close(ajaxRequestTarget);
            }
        });
        add(form);
    }


}
